const DATA_CACHE = []; // 数据缓存
const APIS_LOADED = []; // 记录请求过的 API，避免重复加载
const PERIOD_DOUBLE_CLICK = 500; // 双击判定时间间隔
const PERIOD_ACTION = 240; // 单次动作判定时间间隔
const URL_WINDOWS_VERSION = "https://www.microsoft.com/store/apps/9N7VHQ989BB7";

let img_uhd_next; // 下一张原图缓存
let img_thumb_next; // 下一张缩略图缓存
let img_uhd_prev; // 上一张原图缓存
let img_thumb_prev; // 上一张缩略图缓存
let page = 0; // 页索引
let uhd_last_click = 0; // 图片上鼠标点击/手指触摸上次时间
let caption_expanded = false; // 保持图文详情展开
let mark_cate_how_or_what = true; // true how false what
let time_context_menu = 0; // 上下文菜单弹出时间（避免重复触发）
let timer_flip = null; // 翻页计时器ID
let timer_click = null; // 点击计时器ID
let timer_caption = null; // 图文计时器ID

$(document).ready(function() {
  initShortcut(); // 初始化快捷键
  initMenu(); // 初始化上下文菜单
  initImg(); // 初始化图控件
  initCaption(); // 初始化图文模块
  init(); // 初始化
  load(); // 加载数据
});

function init() {
  if (sessionStorage.getItem("notifyPage")) { // 提示当前页面
    showToastInfo("notify_page", "当前页面：" + sessionStorage.getItem("notifyPage"));
    sessionStorage.removeItem("notifyPage");
  }
  if (PAGE_CURRENT === $("#menu-order-favorite").attr("data-page")) {
    checkAccount();
  }
}

function initShortcut() {
  $(document).keydown(function(e) {
    if (e.keyCode === 13) { // Enter
      e.preventDefault();
      toggleFullScreen();
    } else if (e.keyCode === 32) { // Space
      e.preventDefault();
      // toggleImgFit();
      let uhd = $(".uhd");
      toggleImgFit(uhd.data("data")["centerx"], uhd.data("data")["centery"]);
    } else if (e.keyCode === 37 || e.keyCode === 38) { // Left / Up
      e.preventDefault();
      clearTimeout(timer_flip);
      timer_flip = setTimeout("prev()", PERIOD_ACTION);
    } else if (e.keyCode === 39 || e.keyCode === 40) { // Right / Down
      e.preventDefault();
      clearTimeout(timer_flip);
      timer_flip = setTimeout("next()", PERIOD_ACTION);
    }/* else if (e.keyCode === 8) { // Backspace
      e.preventDefault();
      markDislike();
    } else if (e.keyCode === 46) { // Delete
      e.preventDefault();
      markDelete();
    } else if (e.ctrlKey && e.keyCode === 55) { // Ctrl+7
      e.preventDefault();
      rankJournal();
    } else if (e.ctrlKey && (e.keyCode === 83 || e.keyCode === 68)) { // Ctrl+S / Ctrl+D
      e.preventDefault();
      rankSave();
    } else if (e.ctrlKey && e.keyCode === 88) { // Ctrl+X
      e.preventDefault();
      rankCenter();
    }*/ else if (e.ctrlKey && e.keyCode === 67) {
      e.preventDefault();
      if (e.shiftKey) { // Ctrl+Shift+C
        copyJson();
      } else if (e.altKey) { // Ctrl+Alt+C
        copyId();
      } else { // Ctrl+C
        copyUrl();
      }
    }/* else if (e.ctrlKey && e.keyCode === 70) { // Ctrl+F
      e.preventDefault();
      search();
    } else if (e.ctrlKey && e.keyCode === 71) { // Ctrl+G
      if (URL_API_FIX) { // 支持提交信息修正
        e.preventDefault();
        fix();
      }
    } else if (e.keyCode === 49) { // 1 / Ctrl+1
      e.preventDefault();
      if (mark_cate_how_or_what) {
        // refreshMenuCateHow("general");
        rankCateHow("general", "其他");
      } else {
        // refreshMenuCateWhat("general");
        rankCateWhat("general", "其他");
      }
      mark_cate_how_or_what = !mark_cate_how_or_what;
    } else if (e.keyCode === 50) { // 2 / Ctrl+2
      e.preventDefault();
      if (mark_cate_how_or_what) {
        // refreshMenuCateHow("photography");
        rankCateHow("photography", "摄影");
      } else {
        // refreshMenuCateWhat("landscape");
        rankCateWhat("landscape", "风光");
      }
      mark_cate_how_or_what = !mark_cate_how_or_what;
    } else if (e.keyCode === 51) { // 3 / Ctrl+3
      e.preventDefault();
      // refreshMenuCateWhat("character");
      rankCateWhat("character", "人物");
      mark_cate_how_or_what = true;
    } else if (e.keyCode === 52) { // 4 / Ctrl+4
      e.preventDefault();
      // refreshMenuCateWhat("living");
      rankCateWhat("living", "生灵");
      mark_cate_how_or_what = true;
    } else if (e.keyCode === 53) { // 5 / Ctrl+5
      e.preventDefault();
      markR18();
    }*/ else if (e.keyCode === 49 || e.keyCode === 50) { // TODO: 1 / 2
      e.preventDefault();
      rankQcPass();
    } else if (e.keyCode === 46) { // TODO: Delete
      e.preventDefault();
      rankQcDelete();
    } else if (e.ctrlKey && e.keyCode === 53) { // TODO: Ctrl+5
      e.preventDefault();
      rankQcR18();
    } else if (e.ctrlKey && e.keyCode === 55) { // TODO: Ctrl+7
      e.preventDefault();
      rankQcJournal();
    } else if (e.ctrlKey && e.keyCode === 88) { // TODO: Ctrl+X
      e.preventDefault();
      rankQcWatermark();
    } else if (e.ctrlKey && e.keyCode === 66) { // TODO: Ctrl+B
      e.preventDefault();
      rankQc404();
    }
  });
}

function initMenu() {
  // 标记当前页菜单项
  $(`.menu-group-order[data-page="${PAGE_CURRENT}"] i`).removeClass("hidden");
  // 调整显示模式菜单项图标
  if (COVER_FIT === "contain") {
    $("#menu-fill .menu-item-title").text("切换填充显示"); // 更新菜单项文字
    $("#menu-fill .fa").removeClass("fa-compress").addClass("fa-expand");
  } else {
    $("#menu-fill .menu-item-title").text("切换全图显示"); // 更新菜单项文字
    $("#menu-fill .fa").removeClass("fa-expand").addClass("fa-compress");
  }
  // if (CATE_MARK) { // 支持标记分类（隐藏不重要菜单项腾出空间）
  //   $("#menu-sep-uwp").remove();
  //   $(".menu-group-uwp").remove();
  //   $("#menu-sep-order").remove();
  //   $(".menu-group-order").remove();
  // } else {
  //   $("#menu-sep-ch").remove();
  //   $(".menu-group-ch").remove();
  //   $("#menu-sep-cw").remove();
  //   $(".menu-group-cw").remove();
  // }
  $(document).on("contextmenu", function(e) { // 禁用图片组件的上下文菜单，避免冲突
    if (Date.now() - time_context_menu < 100) { // 避免重复触发
      return;
    }
    time_context_menu = Date.now();
    closeToast();
    if (parseInt($(".menu").css("left")) >= 0) { // 响应浏览器菜单
      hideMenu();
      return;
    }
    e.preventDefault(); // 阻止响应浏览器菜单
    showMenu(e.clientX, e.clientY, $(this));
  });
  $(".menu-mask").click(function() { // 上下文菜单辅助控制层点击事件
    hideMenu();
  });
  $(".menu .menu-item").click(function() { // 菜单项点击事件
    hideMenu();
    switch ($(this).attr("id")) {
      case "menu-fill":
        toggleImgFit();
        break;
      case "menu-copy":
        copyUrl();
        break;
      case "menu-save":
        rankSave();
        break;
      // case "menu-ch-photography":
      // case "menu-ch-general":
      //   refreshMenuCateHow($(this).attr("data-id"));
      //   rankCateHow($(this).attr("data-id"), $(this).attr("data-name"));
      //   break;
      // case "menu-cw-landscape":
      // case "menu-cw-character":
      // case "menu-cw-living":
      // case "menu-cw-general":
      //   refreshMenuCateWhat($(this).attr("data-id"));
      //   rankCateWhat($(this).attr("data-id"), $(this).attr("data-name"));
      //   break;
      case "menu-desktop":
        setDesktopBackground();
        break;
      case "menu-service":
        launchService();
        break;
      // case "menu-order-latest":
      // case "menu-order-trending":
      // case "menu-order-random":
      // case "menu-order-seek":
      // case "menu-order-favorite":
      //   gotoFlipPage($(this).attr("data-page"), $(this).text().trim());
      //   break;
      case "menu-gallery":
        gotoGallery();
        break;
    }
  });
}

function initImg() {
  // 图片缓存
  img_uhd_next = new Image();
  img_thumb_next = new Image();
  img_uhd_prev = new Image();
  img_thumb_prev = new Image();
  // 解决跨域403问题
  // 解决方法2: <meta name="referrer" content="no-referrer">
  img_uhd_next.referrerPolicy = "no-referrer";
  img_thumb_next.referrerPolicy = "no-referrer";
  img_uhd_prev.referrerPolicy = "no-referrer";
  img_thumb_prev.referrerPolicy = "no-referrer";
  let uhd = $(".uhd");
  let thumb = $(".thumb");
  let uhd_hammer = new Hammer(uhd.get(0));
  if (COVER_FIT === "contain") { // 调整图片显示模式（默认为 cover）
    uhd.css("object-fit", "contain");
    thumb.css("object-fit", "contain");
  }
  thumb.on("load", function () { // 缩略图加载完成
    // 淡入缩略图（首次有）
    $(this).addClass("fade-in");
    // 淡出原图
    let uhd = $(".uhd");
    if (parseFloat(uhd.css("opacity")) === 0) { // 原图已淡出
      // resumeImgCenter(uhd); // 重置缩放中心
      resumeImgCenter(uhd, uhd.data("data")["centerx"], uhd.data("data")["centery"]); // 重置缩放中心
      uhd.attr("src", uhd.data("url"));
    }
    uhd.removeClass("fade-in");
  }).on("error", function() {
    $(this).attr("src", PLACEHOLDER);
  });
  uhd.on("load", function () { // 原图加载完成
    // 缓存下一张和上一张
    let page_next = Math.max(Math.min(page + 1, DATA_CACHE.length - 1), 0);
    img_uhd_next.src = DATA_CACHE[page_next]["imgurl"];
    img_thumb_next.src = DATA_CACHE[page_next]["thumburl"];
    let page_prev = Math.max(Math.min(page - 1, DATA_CACHE.length - 1), 0);
    img_uhd_prev.src = DATA_CACHE[page_prev]["imgurl"];
    img_thumb_prev.src = DATA_CACHE[page_prev]["thumburl"];
    // 修复可能缺失的图片信息
    fixInfo();
    // 图文模块非展开状态时隐藏加载指示条
    if (!$(".caption .detail").is(":visible")) {
      $(".caption .separator").hide(200);
    }
    // 淡入原图
    let uhd = $(this);
    if (uhd.data("url") === uhd.attr("src")) { // 避免快速翻页造成图片错乱闪烁
      uhd.addClass("fade-in");
    }
  }).on("error", function() {
    $(this).attr("src", PLACEHOLDER);
    showToastError("img", "当前图片损坏，无法显示");
  }).on("transitionend", function() { // opacity
    let uhd = $(this);
    if (parseFloat(uhd.css("opacity")) === 0) { // 原图淡出完成
      // resumeImgCenter(uhd); // 重置缩放中心
      resumeImgCenter(uhd, uhd.data("data")["centerx"], uhd.data("data")["centery"]); // 重置缩放中心
      uhd.attr("src", $(this).data("url"));
    }
  });
  // uhd.dblclick(function() { // 鼠标双击
  //   toggleFullScreen();
  // });
  uhd.get(0).addEventListener("wheel", function(e) { // 原生鼠标滚轮事件（无需依赖 jquery-mousewheel）
    e.preventDefault();
    clearTimeout(timer_flip);
    if (e.deltaY < 0) { // 鼠标滚轮向前滚动
      timer_flip = setTimeout("prev()", PERIOD_ACTION);
    } else if (e.deltaY > 0) { // 鼠标滚轮向后滚动
      timer_flip = setTimeout("next()", PERIOD_ACTION);
    }
  });
  uhd_hammer.on("tap", function(e) { // 依赖 hammer.js
    clearTimeout(timer_click);
    if (Date.now() - uhd_last_click > PERIOD_DOUBLE_CLICK) { // 点击
      let uhd = $(".uhd");
      let pct_x = e.center.x / uhd.innerWidth();
      let pct_y = e.center.y / uhd.innerHeight();
      timer_click = setTimeout(`toggleImgFit(${pct_x}, ${pct_y})`, PERIOD_ACTION);
    } else { // 双击
      closeToast();
      timer_click = setTimeout("toggleFullScreen()", PERIOD_ACTION);
    }
    uhd_last_click = Date.now();
  });
  uhd_hammer.on("swipeleft swiperight", function(e) { // 左右滑动（结束触发，过程中触发使用 panleft panright）
    if (e.type === "swipeleft") {
      next();
    } else {
      prev();
    }
  });
  // uhd_hammer.on("pressup", function() { // 长按（结束触发，过程中触发使用 press）
  //   closeToast();
  // });
  // 兼容 Safari、兼容移动端 Via 浏览器（Chrome 无需兼容）
  uhd_hammer.on("press", function(e) { // 长按（过程中可触发，结束触发使用 pressup）
    if (Date.now() - time_context_menu < 100) { // 避免重复触发
      return;
    }
    time_context_menu = Date.now();
    closeToast();
    showMenu(e.center.x, e.center.y, $(".uhd")); // 显示上下文菜单
  });
}

function initCaption() {
  let caption = $(".caption");
  let caption_hammer = new Hammer(caption.get(0));
  $(".caption .info a").click(function() { // 图源名点击事件
    gotoGallery();
    return false; // 不再响应 href
  });
  caption.mouseenter(function() { // 鼠标悬停（mouseover 冒泡 mouseenter 不会冒泡）
    clearTimeout(timer_caption);
    expandCaption();
  }).mouseleave(function() { // 鼠标移开（mouseout 冒泡 mouseleave 不会冒泡）
    clearTimeout(timer_caption);
    timer_caption = setTimeout(function() {
      if (caption_expanded) { // 保持展开，无需隐藏
        return;
      }
      collapseCaption();
    }, 800); // 延时隐藏
  }).on("touchstart", function() {
    // return false 避免误触发 mouseenter，原因未知
    // 顺序：touchstart > hammer.tap > mouseenter
    return false;
  });
  caption_hammer.on("tap", function(e) { // 依赖 hammer.js
    clearTimeout(timer_caption);
    if (e.pointerType === "mouse") { // 鼠标模式 mouse
      caption_expanded = !caption_expanded;
      refreshCaptionExpandTag();
    } else { // 触屏模式 touch
      caption_expanded = true;
      if ($(".caption .detail").is(":visible")) { // 隐藏详情
        collapseCaption();
      } else { // 显示详情
        expandCaption();
      }
    }
  });
  caption_hammer.on("swipeleft swiperight", function(e) { // 左右滑动（结束触发，过程中触发使用 panleft panright）
    if (e.type === "swipeleft") {
      clearTimeout(timer_caption);
      $(".caption").css("left", 0).css("right", "auto");
      $(".toast-mask").css("left", 0).css("right", "auto");
      // $(".caption").slideUp(200, function() {
      //   $(".caption").css("left", 0).css("right", "auto").slideDown(200);
      // });
    } else {
      clearTimeout(timer_caption);
      $(".caption").css("left", "auto").css("right", 0);
      $(".toast-mask").css("left", "auto").css("right", 0);
      // $(".caption").slideUp(200, function() {
      //   $(".caption").css("left", "auto").css("right", 0).slideDown(200);
      // });
    }
  });
}

function load() {
  // DATA_CACHE.splice(0); // 清空
  // page = 0; // 重置页索引
  let data = localStorage.getItem("data"); // 图库数据
  localStorage.removeItem("data"); // 一次有效
  let goto_img_id = localStorage.getItem("goto"); // 跳转图ID
  localStorage.removeItem("goto"); // 一次有效
  if (data) { // 方式一: 从图库传递数据
    DATA_CACHE.splice(0); // 清空
    DATA_CACHE.push(...JSON.parse(data)); // 传递数据已处理，无需考虑去重
    for (let [index, item] of DATA_CACHE.entries()) { // 定位页索引
      if (item["id"] === goto_img_id) {
        page = index;
        break;
      }
    }
    refresh();
    return;
  }
  // 方式二: 拉取新数据
  // let cover_img_id = new URL(window.location.href).searchParams.get("id");
  // let cover_img_id = localStorage.getItem("cover");
  // let cover_img_id = $.cookie(`cover-${PROVIDER_ID}`); // 封面图ID
  // $.removeCookie(`cover-${PROVIDER_ID}`, {
  //   domain: location.hostname.split(".").slice(-2).join("."),
  //   path: "/"
  // }); // 一次有效
  let url = generateApiUrl(URL_API, SPLIT_KEY, DATA_CACHE);
  if (APIS_LOADED.indexOf(url) >= 0) { // 避免重复加载
    page = Math.min(page, DATA_CACHE.length - 1);
    refresh();
    return;
  }
  APIS_LOADED.push(url); // 加入历史记录
  fetch(url).then(response => response.json())
    .then(data => { // 加载数据
      if (!data || data["status"] !== 1) {
        showToastError("load", data ? data["msg"] : "接口数据异常");
        return;
      }
      if (SHUFFLE) { // 打乱顺序
        data["data"].sort(() => Math.random() - 0.5);
      }
      let data_img = [];
      if (data["extend"] && data["extend"]["status"] === 1 && data["extend"]["data"].length > 0) {
        data["extend"]["data"][0]["extend"] = true; // 增加辅助字段标记来源，避免干扰分页参数计算
        data_img.push(data["extend"]["data"][0]); // 固定指定ID
      }
      data_img.push(...data["data"]);
      data_img.forEach(item => { // 去重缓存
        item["id"] = item["id"].toString(); // 重要：统一按 string 处理ID
        if (!DATA_CACHE.map(a => a["id"]).includes(item["id"])) {
          DATA_CACHE.push(item);
        }
      });
      if (DATA_CACHE.length === 0) {
        showToastError("load", data["msg"] ? data["msg"] : ("空空如也：" + location.pathname));
      }
      page = Math.min(page, DATA_CACHE.length > 0 ? DATA_CACHE.length - 1 : 0);
      refresh();
    }).catch(err => {
      showToastError("load", err);
    });
}

function refresh() {
  let uhd = $(".uhd");
  let thumb = $(".thumb");
  let data = DATA_CACHE[page];
  if (!data) { // 淡出原图
    uhd.removeClass("fade-in");
    thumb.removeClass("fade-in");
    return;
  }
  // 刷新图文
  $(".title").text(parseTag(data, TITLE, TITLE_ALT, PROVIDER_NAME));
  let story = $(".caption .story");
  story.html(parseStory(data));
  if (story.text()) {
    story.removeClass("collapsed");
  } else {
    story.addClass("collapsed");
  }
  let copyright = $(".caption .copyright a");
  copyright.text(parseTag(data, COPYRIGHT, "", ""));
  if (copyright.text() && copyright.text().trim() !== "@" && copyright.text().trim() !== "©") {
    $(".caption .copyright").removeClass("collapsed");
  } else {
    $(".caption .copyright").addClass("collapsed");
  }
  if (data["srcurl"]) {
    copyright.text(copyright.text() ? copyright.text() + " 🌐" : "");
    copyright.attr("href", data["srcurl"]);
  } else {
    copyright.attr("href", "javascript:");
  }
  let release = $(".caption .release");
  release.text(parseReleaseDate(data));
  if (release.text()) {
    release.removeClass("collapsed");
  } else {
    release.addClass("collapsed");
  }
  $(".caption .info span:last").html(parseInfo(data));
  // // 刷新菜单项
  // refreshMenuCateHow(data["catehowid"]);
  // refreshMenuCateWhat(data["catewhatid"]);
  // 刷新标记
  mark_cate_how_or_what = true;
  // 关闭菜单
  hideMenu();
  // 加载缩略图&原图
  $(".caption .separator").show(200); // 显示加载指示条
  uhd.data("data", data)
    .data("id", data["id"])
    .data("rp", parseTag(data, RAW_PROVIDER, "", ""))
    .data("ri", parseTag(data, RAW_ID, "", ""))
    .data("url", data["imgurl"]);
  // resumeImgCenter(thumb); // 重置缩放中心
  resumeImgCenter(thumb, data["centerx"], data["centery"]); // 重置缩放中心
  thumb.attr("src", data["thumburl"]);
}

function generateApiUrl(url_api, split_key, data_loaded) {
  let user = $.cookie("user") ?? "";
  url_api = url_api.replace("{user}", $.cookie("user") ?? "");  // 顶级域名共享
  url_api = url_api.replace("{pwd}", $.cookie(`pwd-${user}`) ?? "");  // 顶级域名共享
  url_api = url_api.replace("{device}", $.cookie("fingerprint") ?? "");  // 顶级域名共享
  // url_api = url_api.replace("{id}", $.cookie(`cover-${PROVIDER_ID}`) ?? "");
  // $.removeCookie(`cover-${PROVIDER_ID}`, { // domain path 需保持一致才能删除
  //   domain: location.hostname.split(".").slice(-2).join("."),
  //   path: "/"
  // });
  data_loaded = data_loaded.filter(item => !item["extend"]); // 剔除不参与分页计算的元素（浅拷贝）
  if (split_key === "no") {
    let no = data_loaded.length > 0 ?
      data_loaded.sort((a, b) => a["no"] - b["no"])[0]["no"] : 99999999;
    return url_api.replace("{no}", no);
  }
  if (split_key === "score") {
    let score = data_loaded.length > 0 ?
      data_loaded.sort((a, b) => a["score"] - b["score"])[0]["score"] : 99999999;
    return url_api.replace("{score}", score);
  }
  if (split_key === "seed") {
    return url_api.replace("{seed}", Date.now());
  }
  return url_api;
}

function next() { // 下一页
  closeToast(); // 关闭消息
  // page = Math.max(Math.min(page + 1, DATA_CACHE.length - 1), 0);
  if (++page >= DATA_CACHE.length - 1) { // 浏览最后一张时开始加载新数据（提前一张加快缓存）
    load();
  } else {
    refresh();
  }
}

function prev() { // 上一页
  closeToast(); // 关闭消息
  page = Math.max(page - 1, 0);
  refresh();
}

function showMenu(x, y, content) {
  let mask = $(".menu-mask");
  mask.removeClass("collapsed");
  let menu = $(".menu");
  let space = 8; // 页边距
  if (x + menu.outerWidth() + space >= content.width()) {
    x = content.width() - menu.outerWidth() - space;
  }
  if (y + menu.outerHeight() + space >= content.height()) {
    y = content.height() - menu.outerHeight() - space;
  }
  // menu.data("x", x).data("y", y);
  // menu.hide(0, function() {
  //   $(".menu").css("left", $(this).data("x")).css("top", $(this).data("y")).slideDown(200);
  // });
  menu.css("left", x).css("top", y);
}

function hideMenu() {
  $(".menu").css("left", "-999px").css("top", "-999px");
  $(".menu-mask").addClass("collapsed");
}

function expandCaption() {
  $(".caption .separator").show(200);
  $(".caption .detail").show(200, function() {
    refreshCaptionExpandTag();
  });
}

function collapseCaption() {
  if (parseFloat($(".uhd").css("opacity")) > 0) { // 原图加载完成才可隐藏指示条
    $(".caption .separator").hide(200);
  }
  $(".caption .detail").hide(200);
}

function refreshCaptionExpandTag() {
  let tag_pin = $(".caption .info span:first");
  if (caption_expanded) {
    // tag_pin.removeClass("collapsed");
    tag_pin.slideDown();
  } else {
    // tag_pin.addClass("collapsed");
    tag_pin.slideUp();
  }
}

/**
 * 根据图片元数据解析，若使用元数据字段，使用 {} 标记
 * 例："第{phase}期" >> "第32期"
 */
function parseTag(data, tag, tag_alt, def) {
  if (!data || (!tag && !tag_alt)) {
    return def;
  }
  function replacer(match, key, len, _offset, _string) {
    let new_val = data[key] ?? "";
    if (!len) {
      return new_val;
    }
    len = parseInt(len);
    if (new_val && new_val.length > len) {
      new_val = new_val.substring(0, len - 2).trim();
      new_val = new_val.replace(/[，。！？…：；“（]+$/g, "").trim();
      new_val += "……";
    }
    return new_val;
  }
  let out = tag.replace(/\{([^}]+?)(?::(\d+))?}/g, replacer);
  if (!out) {
    out = tag_alt.replace(/\{([^}]+?)(?::(\d+))?}/g, replacer);
  }
  return out ?? def;
}

function parseStory(data) {
  if (!data || !data["story"]) {
    return "";
  }
  return data["story"].replaceAll("\r\n", "<br>").replaceAll("\n", "<br>");
}

// function parseCopyright(data, copyright_prefix) {
//   if (!data || !data["copyright"]) {
//     return "";
//   }
//   let text = copyright_prefix + data["copyright"];
//   if (data["srcurl"]) {
//     text += " 🌐";
//   }
//   return text;
// }

function parseReleaseDate(data) {
  if (!data || !data["reldate"]) {
    return "";
  }
  let date = new Date(data["reldate"]);
  let day_of_week = "星期" + "日一二三四五六".charAt(date.getDay());
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日, ${day_of_week}`;
}

function parseInfo(data) {
  if (!data) {
    return "";
  }
  let info = "";
  if (data["catehowid"] && data["catehowid"] !== "general" && data["catehowname"]) {
    info += `&nbsp;&#xb7;&nbsp;${data["catehowname"]}`;
  }
  if (data["catewhatid"] && data["catewhatid"] !== "general" && data["catewhatname"]) {
    info += `&nbsp;&#xb7;&nbsp;${data["catewhatname"]}`;
  }
  if (data["width"] && data["height"]) {
    info += ` / ${data["width"]}x${data["height"]}`;
    if (data["size"]) {
      info += `, ${(data["size"] / 1024 / 1024).toFixed(1)}MB`;
    }
  } else {
    info += " / 0x0";
  }
  return info;
}

/**
 * 当图片加载完成时检查修复图片信息
 * 可修复分辨率，文件大小无法获取
 */
function fixInfo() {
  let img = $(".uhd");
  // jQuery对象转JavaScript对象，使用原生方法获取原图尺寸
  let width = img.get(0).naturalWidth;
  let height = img.get(0).naturalHeight;
  if (width > 0 && height > 0) {
    let info = $(".caption .info span:last");
    if (info.text().indexOf("0x0") >= 0) {
      info.text(info.text().replace("0x0", `${width}x${height}`));
    }
  }
}

function toggleImgFit(pctX=0.5, pctY=0.5) {
  let uhd = $(".uhd");
  let thumb = $(".thumb");
  if (uhd.css("object-fit") === "cover") { // 切换全图
    uhd.css("object-position", "center center")
      .css("object-fit", "contain");
      // .css("cursor", "zoom-in");
    thumb.css("object-position", "center center")
      .css("object-fit", "contain");
      // .css("cursor", "zoom-in");
    $("#menu-fill .menu-item-title").text("切换填充显示"); // 更新菜单项文字
    $("#menu-fill .fa").removeClass("fa-compress").addClass("fa-expand");
    showToastInfo("img-fit", "图片显示模式：全图");
  } else { // 切换填充
    if (pctX >= 0 && pctX >= 0) { // 根据目标位置针对性缩放
      uhd.css("object-position", `${pctX * 100}% ${pctY * 100}%`)
        .css("object-fit", "cover");
        // .css("cursor", "zoom-out");
      thumb.css("object-position", `${pctX * 100}% ${pctY * 100}%`)
        .css("object-fit", "cover");
        // .css("cursor", "zoom-out");
    } else { // 居中填充
      uhd.css("object-position", "center center")
        .css("object-fit", "cover");
        // .css("cursor", "zoom-out");
      thumb.css("object-position", "center center")
        .css("object-fit", "cover");
        // .css("cursor", "zoom-out");
    }
    $("#menu-fill .menu-item-title").text("切换全图显示"); // 更新菜单项文字
    $("#menu-fill .fa").removeClass("fa-expand").addClass("fa-compress");
    showToastInfo("img-fit", "图片显示模式：填充");
  }
}

function resumeImgCenter(img, pctX=0.5, pctY=0.5) {
  if (img.css("object-fit") !== "cover") { // 非填充模式不处理
    return;
  }
  if (pctX >= 0 && pctY >= 0) {
    img.css("object-position", `${pctX * 100}% ${pctY * 100}%`);
  } else { // 默认居中
    img.css("object-position", "center center");
  }
}

function toggleFullScreen() {
  if (!document.fullscreenElement) { // 切换全屏
    document.documentElement.requestFullscreen().then();
  } else if (document.exitFullscreen) { // 退出全屏
    document.exitFullscreen().then();
  }
}

function showToast(id, icon, msg, action, action_func) {
  /*
   * <div class="toast mb8 collapsed">
   *   <i class="fa fa-circle"></i>&emsp;
   *   <span class="msg">消息</span>&emsp;
   *   <a class="action collapsed" href="javascript:">&emsp;关闭&emsp;</a>
   * </div>
   */
  let mask = $(".toast-mask");
  if (!id || !msg) { // 清空消息
    mask.empty();
    return;
  }
  let toast = $(`.toast[data-id="${id}"]`);
  if (toast) { // 移除同类消息
    toast.remove();
  }
  toast = $("<div class='toast mb8 collapsed'></div>");
  toast.attr("data-id", id);
  // 构造消息图标
  let toast_icon = $("<i class='fa fa-circle'></i>");
  if (icon === "error") { // 错误
    toast_icon.addClass("icon-error");
  } else { // 默认
    toast_icon.addClass("icon-info");
  }
  // 构造消息内容
  let toast_msg = $("<span class='msg'></span>");
  toast_msg.html(msg.replaceAll("\r\n", "<br>").replaceAll("\n", "<br>"));
  toast.append(toast_icon).append("&emsp;").append(toast_msg).append("&emsp;");
  // 构造消息按钮
  if (action) {
    let toast_action = $("<a class='action' href='javascript:'></a>");
    toast_action.html("&emsp;" + action + "&emsp;");
    if (action_func) {
      toast_action.click(function() {
        // closeToast();
        $(this).parents(".toast").remove();
        action_func();
      });
    } else {
      toast_action.click(function() {
        // closeToast();
        $(this).parents(".toast").remove();
      });
    }
    toast.append(toast_action);
  }
  mask.prepend(toast);
  $(".toast:gt(2)").remove(); // 移除多余消息，保留3条
  toast.show();
}

function showToastInfo(id, msg, action, action_func) {
  showToast(id, "info", msg, action, action_func);
}

function showToastError(id, msg, action, action_func) {
  showToast(id, "error", msg, action, action_func);
}

function closeToast() {
  showToast(null, null, null, null, null);
}

// function refreshMenuCateHow(id) {
//   $(".menu-group-ch").each(function () {
//     if ($(this).attr("data-id") === id) {
//       $(this).children(".fa").removeClass("hidden");
//     } else {
//       $(this).children(".fa").addClass("hidden");
//     }
//   });
// }

// function refreshMenuCateWhat(id) {
//   $(".menu-group-cw").each(function () {
//     if ($(this).attr("data-id") === id) {
//       $(this).children(".fa").removeClass("hidden");
//     } else {
//       $(this).children(".fa").addClass("hidden");
//     }
//   });
// }

function markR18() {
  let data = $(".uhd").data("data");
  if (!data) {
    return;
  }
  rankR18();
}

function markDislike() {
  let data = $(".uhd").data("data");
  if (!data) {
    return;
  }
  rankDislike();
}

function markDelete() {
  let data = $(".uhd").data("data");
  if (!data) {
    return;
  }
  if (!data["catehowid"]) {
    rankCateHow("general", "其他");
  }
  if (!data["catewhatid"]) {
    rankCateWhat("general", "其他");
  }
  rankDelete();
}

function gotoGallery() {
  // let last_page = new URL(document.referrer ? document.referrer : location.href);
  // if (last_page.hostname === location.hostname && last_page.pathname.indexOf("/flip") !== 0) {
  //   window.history.back();
  //   return;
  // }
  let uhd = $(".uhd");
  // 通过顶级域名 cookie 传递图片ID，使其出现在顶部（localhost 127.0.0.1 会出错）
  $.cookie(`cover-${PROVIDER_ID}`, uhd.data("id"), {
    domain: location.hostname.split(".").slice(-2).join("."),
    path: "/"
  });
  let url = location.pathname.replace("/flip", "");
  location.assign(url); // 记入历史页面（可回退）
  // location.replace(url); // 不会记入历史页面（不可回退）
}

function gotoFlipPage(page, name) {
  sessionStorage.setItem("notifyPage", name);
  location.replace(page); // 不会记入历史页面（不可回退）
}

function setDesktopBackground() {
  let text = "网页版不支持设置桌面或锁屏背景，您可以安装「拾光壁纸」桌面版本，以体验快速设置壁纸等更多功能。" +
    "\n安装方法：在 Microsoft Store 搜索「拾光壁纸」。";
  showToastError("uwp", text, "前往安装", function() {
    window.open(URL_WINDOWS_VERSION);
  });
}

function launchService() {
  let text = "网页版不支持推送桌面或锁屏背景，您可以安装「拾光壁纸」桌面版本，以体验自动更换壁纸等更多功能。" +
    "\n安装方法：在 Microsoft Store 搜索「拾光壁纸」。";
  showToastError("uwp", text, "前往安装", function() {
    window.open(URL_WINDOWS_VERSION);
  });
}

function copyJson() {
  let data = $(".uhd").data("data");
  navigator.clipboard.writeText(JSON.stringify(data, null, 2)).then(function() {
    showToastInfo("copy", "已复制 JSON 信息");
  }, function() {
    showToastError("copy", "复制失败");
  });
}

function copyId() {
  navigator.clipboard.writeText($(".uhd").data("ri")).then(function() {
    showToastInfo("copy", "已复制图片 ID");
  }, function() {
    showToastError("copy", "复制失败");
  });
}

function copyUrl() {
  rankCopy();
  navigator.clipboard.writeText($(".uhd").attr("src")).then(function() {
    showToastInfo("copy", "已复制原图链接");
  }, function() {
    showToastError("copy", "复制失败");
  });
}

function rankCopy() {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "copy",
    undo: 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (!data || data["status"] !== 1) {
        showToastError("rank-copy", "同步复制失败");
      }
    })
    .catch(err => {
      showToastError("rank-copy", "同步复制出错：" + err);
    });
}

function rankSave(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "save",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          // showToastInfo("rank-save", "已收藏", "撤销", function() {
          //   rankSave(true);
          // });
          showToastInfo("rank-save", "已收藏", "查看", function() {
            // let menu_page = $("#menu-order-favorite");
            // gotoFlipPage(menu_page.attr("data-page"), menu_page.text().trim());
            gotoFlipPage("/flip/favorite", "收藏");
          });
        }
      } else {
        showToastError("rank-save", undo ? "撤销收藏出错" : "收藏出错");
      }
    })
    .catch(err => {
      showToastError("rank-save", "收藏出错：" + err);
    });
}

function rankCenter(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  if (img.css("object-fit") !== "cover") { // 不支持非填充模式
    showToastError("rank-center", "标记失败：请切换至填充模式");
    return;
  }
  // jQuery对象转JavaScript对象，使用原生方法获取原图尺寸
  let width = img.get(0).naturalWidth;
  let height = img.get(0).naturalHeight;
  if (width < 0 || height < 0) {
    showToastError("rank-center", "标记失败：无法解析图像尺寸");
    return;
  }
  let center_x = 0.5; // 中心点百分比坐标 x
  let center_y = 0.5; // 中心点百分比坐标 y
  let position = img.css("object-position");
  let match = position.match(/^([\d\\.]+)%\s+([\d\\.]+)%$/);
  if (!match) {
    showToastError("rank-center", "标记失败：无法解析“" + position + "”");
    return;
  }
  if (width > height) { // 横图，只标记水平中心点
    center_x = parseFloat(match[1]) / 100;
  } else { // 竖图，只标记垂直中心点
    center_y = parseFloat(match[2]) / 100;
  }
  let center = `${center_x.toFixed(4)},${center_y.toFixed(4)}`; // 4位精度即可
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "center",
    target: center,
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          let center = data["data"]["target"].match(/^([\d\\.]+),([\d\\.]+)$/);
          let x = `${Math.round(parseFloat(center[1]) * 1000) / 10}%`;
          let y = `${Math.round(parseFloat(center[2]) * 1000) / 10}%`;
          showToastInfo("rank-center", `已标记中心点：(${x}, ${y})`, "撤销", function() {
            rankCenter(true);
          });
        }
      } else {
        showToastError("rank-center", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-center", "标记出错：" + err);
    });
}

function rankCateHow(id, name) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "catehow",
    target: id,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        showToastInfo("rank-cate-how", "已标记分类1：" + name);
      } else {
        showToastError("rank-cate-how", "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-cate-how", "标记出错：" + err);
    });
}

function rankCateWhat(id, name) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "catewhat",
    target: id,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        showToastInfo("rank-cate-what", "已标记分类2：" + name);
      } else {
        showToastError("rank-cate-what", "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-cate-what", "标记出错：" + err);
    });
}

function rankDelete(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "delete",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-delete", "已标记：删除", "撤销", function() {
            rankDelete(true);
          });
        }
      } else {
        showToastError("rank-delete", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-delete", "标记出错：" + err);
    });
}

function rankDislike(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "dislike",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-dislike", "已标记：我不喜欢", "撤销", function() {
            rankDislike(true);
          });
        }
      } else {
        showToastError("rank-dislike", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-dislike", "标记出错：" + err);
    });
}

function rankR18(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "r18",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-r18", "已标记：有色气", "撤销", function() {
            rankR18(true);
          });
        }
      } else {
        showToastError("rank-r18", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(err => {
      showToastError("rank-r18", "标记出错：" + err);
    });
}

function rankJournal(undo=false) {
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "journal",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-journal", "已标记：周度精选", "撤销", function() {
            rankJournal(true);
          });
        }
      } else {
        showToastError("rank-journal", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function search() {
  if (confirm("调用 Google 以图搜图？")) {
    let img_url = $(".uhd").attr("src");
    let search_url = "https://lens.google.com/uploadbyurl?url=" + encodeURIComponent(img_url);
    window.open(search_url, "_blank");
  }
}

function fix() {
  let cmd = prompt(HINT_FIX ? HINT_FIX : "反馈");
  if (!cmd) {
    return;
  }
  let url_api = URL_API_FIX.replace("{id}", $(".uhd").data("id"))
    .replace("{cmd}", encodeURIComponent(cmd));
  fetch(url_api).then(function(response) {
    response.json().then(function(res) {
      if (res && res["status"] === 1) {
        showToastInfo("fix", res["msg"] ? res["msg"] : "提交成功");
      } else {
        showToastError("fix", "提交出错");
      }
    });
  }).catch(err => {
    showToastError("fix", "提交出错：" + err);
  });
}

function checkAccount() {
  let user = $.cookie("user") ?? "";
  let pwd_en = $.cookie(`pwd-${user}`) ?? "";
  let device_id = $.cookie("fingerprint") ?? "";
  if (!user) {
    showToastError("account", "当前未绑定帐号，您的收藏数据可能丢失", "前往绑定", function() {
      window.open("/account");
    });
    return;
  }
  let url = `https://api.nguaduot.cn/appstats/account?user=${user}&pwd=${pwd_en}&device=${device_id}`;
  fetch(url)
    .then(response => response.json())
    .then(data => {
      if (!data || data["status"] !== 1) {
        showToastError("account", "帐号验证失败：" + (data ? data["msg"] : "接口数据异常"));
      } else if (!data["data"]["active"] || !data["data"]["auth"]) {
        showToastError("account", "当前未绑定帐号，您的收藏数据可能丢失", "前往绑定", function() {
          window.open("/account");
        });
      }
    })
    .catch(err => {
      showToastError("account", "帐号验证失败：" + err);
    });
}

function rankQcPass(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "pass",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-delete", "已标记：已审查", "撤销", function() {
            rankQcPass(true);
          });
        }
      } else {
        showToastError("rank-delete", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function rankQcDelete(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "delete",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-delete", "已标记：低质量", "撤销", function() {
            rankQcDelete(true);
          });
        }
      } else {
        showToastError("rank-delete", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function rankQcR18(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "r18",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-r18", "已标记：色图", "撤销", function() {
            rankQcR18(true);
          });
        }
      } else {
        showToastError("rank-r18", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function rankQcJournal(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "journal",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-journal", "已标记：好图推荐", "撤销", function() {
            rankQcJournal(true);
          });
        }
      } else {
        showToastError("rank-journal", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function rankQcWatermark(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "watermark",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-delete", "已标记：含水印", "撤销", function() {
            rankQcWatermark(true);
          });
        }
      } else {
        showToastError("rank-delete", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}

function rankQc404(undo=false) { // TODO
  if (!$.cookie("fingerprint")) {
    return;
  }
  let img = $(".uhd");
  let data_req = {
    provider: img.data("rp"),
    imgid: img.data("ri"),
    imgurl: img.attr("src"),
    action: "404",
    undo: undo ? 1 : 0,
    deviceid: $.cookie("fingerprint"),
    client: CLIENT
  };
  fetch("https://api.nguaduot.cn/appstats/rank/qc", {
    method: "POST",
    body: JSON.stringify(data_req)
  }).then(response => response.json())
    .then(data => {
      if (data && data["status"] === 1) {
        if (!undo) {
          showToastInfo("rank-delete", "已标记：图片损坏", "撤销", function() {
            rankQc404(true);
          });
        }
      } else {
        showToastError("rank-delete", undo ? "撤销标记出错" : "标记出错");
      }
    })
    .catch(console.error);
}